package com.fjwt.gz.coupon.yspay;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.aliyun.oss.ServiceException;
import com.wechat.pay.java.core.notification.NotificationConfig;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import jakarta.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.TreeMap;

@Service
@Slf4j
public class YspayCouponWriteNotifyService {

    private static final Logger ysPayLogger = LoggerFactory.getLogger("ysPay");
    private static String logPrefix = "银盛卡券核销回调:";



    public Map<String, Object> paraseParamters(HttpServletRequest request, NotificationConfig notificationConfig) throws IOException {
        ysPayLogger.info(logPrefix + "request:{}", JSONUtil.toJsonStr(request));
        Map<String, Object> map = getCouponNotifyParams(request);
        ysPayLogger.info(logPrefix + "解析参数返回的信息是：{}", JSONUtil.toJsonStr(map));
        return map;
    }


    /**
     * 获取通知参数 公共方法
     *
     * **/
    public static Map<String, Object> getCouponNotifyParams(HttpServletRequest request){
        TreeMap<String, Object> treeMap = new TreeMap<String, Object>();
        InputStreamReader in = null;
        try {
            in = new InputStreamReader(request.getInputStream(), StandardCharsets.UTF_8);
            StringBuffer bf = new StringBuffer();
            int len;
            char[] chs = new char[1024];
            while ((len = in.read(chs)) != -1) {
                bf.append(new String(chs, 0, len));
            }
            ysPayLogger.info("请求头部取数据bf：{}",bf);
            String decodedString = URLDecoder.decode(bf.toString(), "UTF-8");
            ysPayLogger.info("请求头部取数据tostring,decodedString：{}",decodedString);
            // 判断 bf 中是否包含 & 符号
            if (decodedString.contains("&")) {

                ysPayLogger.info("bf 中包含 & 符号");

                // 处理包含 & 符号的情况
                String[] split1 = decodedString.split("&");
                treeMap = new TreeMap<>();
                for (String en : split1) {
                    String[] split = en.split("=");
                    if (split.length == 2) {
                        treeMap.put(split[0], split[1]);
                    } else {
                        ysPayLogger.warn("键值对格式不正确: {}", en);
                    }
                }
                return treeMap;

            } else {
                ysPayLogger.info("bf 中不包含 & 符号");
                // 处理不包含 & 符号的情况
                JSONObject jsonObject = JSONObject.parseObject(String.valueOf(bf));
                ysPayLogger.debug("银盛异步回调参数转换：{}", jsonObject.toJSONString());

                // 将 JSONObject 转换为 Map
                treeMap = new TreeMap<>(jsonObject);

                return treeMap;
            }
        } catch (Exception e) {
            ysPayLogger.error("请求头部取数据异常：{}", e.getMessage());
            throw new ServiceException(e.getMessage());
        } finally {
            if (null != in) {
                try {
                    in.close();
                } catch (Exception e) {
                    ysPayLogger.error("流关闭异常:{}", e.getMessage());
                }
            }
        }
    }

}
